package P19;

import org.junit.Test;

/**
 * @Author DJ同学
 * @Date 2021/2/23 23:16
 * @Version 1.0
 * @Name 删除链表的倒数第 N 个结点
 * @Problem https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/
 * 快慢指针 让快慢指针隔了n个单位 当快指针的next=null,删除慢指针的next节点
 */
public class Solution {
    @Test
    public void test(){
//        ListNode root  = new ListNode(1);
//        root.next = new ListNode(2);
//        root.next.next = new ListNode(3);
//        root.next.next.next = new ListNode(4);
//        root.next.next.next.next = new ListNode(5);
//        root.next.next.next.next.next = null;
//        ListNode listNode = removeNthFromEnd(root, 2);
        System.out.println("----------------------");
        ListNode root  = new ListNode(1);
        root.next =null;
        ListNode listNode = removeNthFromEnd(root, 1);
        System.out.println("----------------------");
    }

    public ListNode removeNthFromEnd(ListNode head, int n) {
        if(head==null) return null;
        ListNode fast  = head;
        //先移动fast
        int i;
        for(i=0;i<n&&fast!=null;i++){
            fast=fast.next;
        }
        //链表长度不够删除
        if(i<n){
            return head;
        }
        ListNode slow = head;
        while(fast!=null&&fast.next!=null){
            slow = slow.next;
            fast = fast.next;
        }
        //fast=null 删除头节点 比如5个节点，删除倒数第5个
        if(fast==null){
            head = head.next;
        }
        //fast.next=null 正常情况下的删除
        else{
            ListNode next = slow.next;
            slow.next = next.next;
        }
        return head;
    }
}
